# 读取元数据，存储软件包间依赖关系


from py2neo import Node, NodeMatcher, Relationship, Subgraph

from graph_util import *

graph = get_graph()
matcher = NodeMatcher(graph)


# 查询节点，按照name查询，无返回None
def match_node(label, **prop):
    node = matcher.match(label).where(**prop).first()
    return node


def match_all_to_dict(label):
    nodes = matcher.match(label).all()
    return {node['id']: node for node in nodes}


def loop_store_rel():
    """ 循环存储关系
    """
    pkgs_json = load_pkgs()
    for name, val1 in pkgs_json.items():
        for version, pkg in val1.items():
            pkg_node = match_node('Package', id=name + version)
            for dependency in pkgs_json[name][version]['dependencies']:
                dependency_node = match_node('Package', id=dependency['name'] + dependency['version'])
                # if dependency_node is None:
                #     dependency_node = dependency
                #     dependency_node['expired'] = 'true'
                #     dependency_node = Node('Package', **dependency_node)
                #     graph.create(dependency_node)
                graph.create(Relationship(dependency_node, 'depends_on', pkg_node))
            print(f'{name}{version}关系已处理 ', end='')
        print()


def batch_store_rel():
    """ 批量存储所有关系，大幅提升速度
    """
    pkgs_json = load_pkgs()
    relations = []
    pkg_dict = match_all_to_dict('Package')
    for name, val1 in pkgs_json.items():
        for version, pkg in val1.items():
            pkg_node = pkg_dict[name + version]
            for dependency_id in pkgs_json[name][version]['dependencies']:
                relations.append(Relationship(pkg_dict[dependency_id], 'depends_on', pkg_node))
    tx = graph.begin()
    graph.create(Subgraph(relationships=relations))
    graph.commit(tx)


if __name__ == '__main__':
    batch_store_rel()
